import BraftEditor from 'braft-editor';
import { useEffect, useState } from 'react';
import 'braft-editor/dist/index.css';
// TODO：该方法需要自定义 例如：
// export const uploadFile = (fileData: Record<string, string | File>,options:ProgressTypes={}) => {
//   const data = new FormData()
//   Object.keys(fileData).forEach((key: string) => {
//     data.append(key, fileData[key])
//   })
//   return request('/common/upload', {
//     method: 'POST',
//     data,
//     headers: {
//       'Content-Type': 'multipart/form-data'
//     },
//     transformRequest: [function (data) {
//       return data
//     }],
//     ...options
//   })
// }

import { uploadFile } from '@/services/ant-design-pro/api';
export const TextEditor = (
  props: {
    value?: string;
    onChange?: (value?: string) => string | undefined;
  } = {},
) => {
  const [data, setData] = useState<any>({});
  const initContent = (c = '') => {
    const editorState = BraftEditor.createEditorState(c || '');
    return editorState;
  };
  useEffect(() => {
    if (props.value) {
      const contentStatus = initContent(props.value);
      data.contentStatus = contentStatus;
      setData({ ...data });
    }
  }, []);
  const uploadFn = (param: TextMediaParamsType) => {
    const successFn = (response: any) => {
      // 上传成功后调用param.success并传入上传后的文件地址
      param.success({
        url: response.url,
      })
    }
    const progressFn = (event: ProgressEvent) => {
      // 上传进度发生变化时调用param.progress
      param.progress(event.loaded / event.total * 100)
    }
    const errorFn = (response: any) => {
      // 上传发生错误时调用param.error
      param.error({
        msg: 'unable to upload.'
      })
    }
    const options: ProgressTypes = {
      onUploadProgress: progressFn,
    }

    uploadFile({ file: param.file }, options).then((res: any) => {
      if (res.code === 200) {
        successFn(res)
      } else {
        errorFn(res)
      }
    }).catch((err: any) => {
      errorFn(err)
    })
  }
  return (
    <BraftEditor
      placeholder="请输入内容"
      style={{ border: '1px solid #ccc' }}
      value={data?.contentStatus}
      media={{ uploadFn }}
      onChange={(e: any) => {
        data.contentStatus = e;
        setData({ ...data });
        if (props && props.onChange) {
          props.onChange(e.toHTML());
        }
      }}
    />
  );
};
